Tutorial Brief

This tutorial is an introduction to Python 3. This should give you the set of pythonic skills that you will need to proceed with this tutorial series.

If you don't have the Jupyter installed, shame on you. No just kidding you can follow this tutorial using an online jupyter service:

https://try.jupyter.org/

Cell Input and Output


In [1]:
1+2


Out[1]:
3

In [2]:
1+1
1+2


Out[2]:
3

The print function

Notice: print is a function in Python 3. You should use parentheses around your parameter.


In [3]:
print(1+2)


3

Variables

There are many variable types in Python 3. Here is a list of the most common types:

Numerical Types:

  • bool (Boolean)
  • int (Integer/Long)
  • float
  • complex

Notice: In Python 3 integer represents integer and long. Because there is no more long data type, you will not get L at the end of long integers.


In [4]:
a = 4
b = 1.5
c = 121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212
d = 1j
e = 1/3
f = True

In [5]:
a+b


Out[5]:
5.5

In [6]:
a*c


Out[6]:
484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848484848

In [7]:
(b+d)*a


Out[7]:
(6+4j)

In [8]:
a+f


Out[8]:
5

In [9]:
type(1.5)


Out[9]:
float

Other Value Types:

  • str (String)
  • list (Ordered Array)
  • tuple (Ordered Immutable Array)
  • dict (Unordered list of keys and values)

In [10]:
my_name = "Roshan"
print(my_name)


Roshan

In [11]:
my_list = [1,2,3,4,5]
my_list


Out[11]:
[1, 2, 3, 4, 5]

In [12]:
my_list + [6]


Out[12]:
[1, 2, 3, 4, 5, 6]

In [13]:
my_list


Out[13]:
[1, 2, 3, 4, 5]

In [14]:
my_list += [6,7,8]
my_list


Out[14]:
[1, 2, 3, 4, 5, 6, 7, 8]

In [15]:
my_list.append(9)
my_list


Out[15]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

In [16]:
my_tuple = (1,2,3)
my_tuple


Out[16]:
(1, 2, 3)

In [17]:
my_tuple + (4,5,6)


Out[17]:
(1, 2, 3, 4, 5, 6)

In [18]:
my_dict = {"name":"Roshan", "credit":100}
my_dict


Out[18]:
{'credit': 100, 'name': 'Roshan'}

In [19]:
my_dict["name"]


Out[19]:
'Roshan'

In [20]:
my_dict["level"] = 4
my_dict


Out[20]:
{'credit': 100, 'level': 4, 'name': 'Roshan'}

In [21]:
my_dict.values()


Out[21]:
dict_values([100, 'Roshan', 4])

In [22]:
my_dict.keys()


Out[22]:
dict_keys(['credit', 'name', 'level'])

Selecting / Slicing

Use len function to measure the length of a list.


In [23]:
len(my_list)


Out[23]:
9

To access a single value in a list use this syntax:

list_name[index]

In [24]:
my_list[0]


Out[24]:
1

To select multiple value from a list use this syntax:

index[start:end:step]

In [25]:
my_list[1:2]


Out[25]:
[2]

In [26]:
my_list[:3]


Out[26]:
[1, 2, 3]

In [27]:
my_list[3:]


Out[27]:
[4, 5, 6, 7, 8, 9]

Notice: negative index selected from the end of the list


In [28]:
my_list[-1]


Out[28]:
9

In [29]:
my_list[-2]


Out[29]:
8

You can use negative indexing in selecting multiple values.


In [30]:
my_list[-2:]


Out[30]:
[8, 9]

In [31]:
my_list[:-2]


Out[31]:
[1, 2, 3, 4, 5, 6, 7]

In [32]:
my_list[3:-1]


Out[32]:
[4, 5, 6, 7, 8]

The third location in the index is the step. If the step is negative the the list is returned in descending order.


In [33]:
my_list[::2]


Out[33]:
[1, 3, 5, 7, 9]

In [34]:
my_list[3::2]


Out[34]:
[4, 6, 8]

In [35]:
my_list[::-1]


Out[35]:
[9, 8, 7, 6, 5, 4, 3, 2, 1]

Working with Strings

You can select from a string like a list suing this syntax:

my_string[star:end:step]

In [36]:
my_name


Out[36]:
'Roshan'

In [37]:
my_name[0]


Out[37]:
'R'

Notice: You can also use negative indexing.


In [38]:
my_name[:2]


Out[38]:
'Ro'

Unicode

Notice: You can use unicode inside your string variables. Unlike Python 2, no need to use u"" to use unicode.


In [39]:
# Sorted by most spoken languages in order
divide_by_zero = {"zho":"你不能除以零",
                  "eng":"You cannot divide by zero",
                  "esp":"No se puede dividir por cero",
                  "hin":"आप शून्य से विभाजित नहीं किया जा सकता \u2248",
                  "arb":"لا يمكن القسمة على صفر"}

print(divide_by_zero["hin"])
type(divide_by_zero["hin"])


आप शून्य से विभाजित नहीं किया जा सकता ≈
Out[39]:
str

String Formatting

You can use this syntax to format a string:

some_variable = 50
x = "Value: %s" % some_variable
print(x) # Value: 50

In [40]:
first_name = "Roshan"
last_name = "Rush"
formatted_name = "%s, %s." % (last_name, first_name[0])
print(formatted_name)


Rush, R.

Other formatters could be used to format numbers:


In [41]:
print("π ≈ %.2f" % 3.14159)


π ≈ 3.14

In [42]:
homeworks = 15.75
midterm = 22
final = 51
total = homeworks + midterm + final

print("Homeworks: %.2f\nMid-term: %.2f\nFinal: %.2f\nTotal: %.2f/100" % (homeworks, midterm, final, total))


Homeworks: 15.75
Mid-term: 22.00
Final: 51.00
Total: 88.75/100

Using format(*args, **kwargs) function


In [43]:
url = "http://{language}.wikipedia.org/"
url = url.format(language="en")
url


Out[43]:
'http://en.wikipedia.org/'

Mathematics


In [44]:
1+1


Out[44]:
2

In [45]:
4-5


Out[45]:
-1

Notice: The default behavior of division in Python 3 is float division. To use integer division like Python 2, use //


In [46]:
14/5


Out[46]:
2.8

In [47]:
14//5


Out[47]:
2

In [48]:
2*5


Out[48]:
10

To raise a number to any power use down asterisk **. To represent $a^{n}$:

a**n

In [49]:
2**3


Out[49]:
8

To calculate the remainder (modulo operator) use %. To represent $a \mod b = r$:

a % b # Returns r

In [50]:
10 % 3


Out[50]:
1

You can

You can use the math library to access a varaity of tools for algebra and geometry. To import a library, you can use one of these syntaxes:

import library_name
import library_name as alias
from module_name import some_class

In [51]:
import math

In [52]:
n=52
k=1
math.factorial(n) / (math.factorial(k) * math.factorial(n-k))


Out[52]:
52.0

Loops


In [53]:
for counter in [1,2,3,4]:
    print(counter)


1
2
3
4

range

In Python 3 range is a data type that generates a list of numbers.

range(stop)
range(start,stop[ ,step])

Notice: In Python 2 range is a function that returns a list. In Python 3, range returns an iterable of type range. If you need to get a list you can use the list() function:

list(range(start,stop[, step]))

In [54]:
for counter in range(5):
    print(counter)


0
1
2
3
4

Notice: The list doesn't reach the stop value and stops one step before. The reason behind that is to make this syntax possible:


In [55]:
list(range(1,10)) == list(range(1,5)) + list(range(5,10))


Out[55]:
True

Notice: In Python 3 use use == to check if two values are equal. To check if two values are not equal use != and don't use <> from Python 2 because it is not supported any more in Python 3.


In [56]:
for counter in range(1,5):
    print(counter)


1
2
3
4

In [57]:
for counter in range(2,10,2):
    print(counter)


2
4
6
8

While Loop


In [58]:
counter =1
while counter < 5:
    print(counter)
    counter += 1


1
2
3
4

If .. Else


In [59]:
if math.pi == 3.2:
    print("Edward J. Goodwin was right!")
else:
    print("π is irrational")


π is irrational

In [60]:
if math.sqrt(2) == (10/7):
    print("Edward J. Goodwin was right!")
elif math.sqrt(2) != (10/7):
    print("Square root of 2 is irrational")


Square root of 2 is irrational

If you like Math:

Fun story about pi where it was almost set by law to be equal to 3.2!

If you don't what is the "pi bill" you can read about it here: http://en.wikipedia.org/wiki/Indiana_Pi_Bill

Or watch Numberphile video about it: https://www.youtube.com/watch?v=bFNjA9LOPsg


In [61]:
probability = 0.3

if probability >= 0.75:
    print("Sure thing")
elif probability >= 0.5:
    print("Maybe")
elif probability >= 0.25:
    print("Unusual")
else:
    print("No way")


Unusual

Functions

Functions are defined in Python using def keyword.


In [62]:
def get_circumference(r):
    return math.pi * r * 2

In [63]:
get_circumference(5)


Out[63]:
31.41592653589793

In [64]:
def binomilal_coef(n,k):
    """
    This function returns the binominal coef
    
    Parameters:
    ===========
    n, k int
    
    return n!/(k!*(n-k)!)
    """
    value = math.factorial(n)/(math.factorial(k)*math.factorial(n-k))
    return value


binomilal_coef(52,2)


Out[64]:
1326.0

Notice: Use can use SHIFT+TAB to show the docstring of a function.

If You Like Math

This was the binomial function which tells you how many ways are there to select k number of samples from a sample space with n items if order didn't matter and chosen samples could not be repeated (chosen again).

As an example, How many ways to select 2 card from a deck of 52 cards if order of selection didn't matter and you where not allowed to choose the same card twice?

$${n \choose k} = {n! \over {k!(n-k)!}}$$$${52 \choose 2} = {52! \over {2!(52-2)!}} = {52! \over {2!(50)!}} = 1326$$

Quick Quiz:

How many ways to select 2 cards from a deck of 52 cards if order didn't matter and you could choose the same card twice?

hints:

$$\left(\!\!\!\binom{52}{2}\!\!\!\right) = {{52+2-1} \choose 2} = {{53} \choose 2} = \frac{53!}{2!(51)!}$$
  • If you got 1326 then you got it WRONG.

Last quiz was solved by:

pacrii